//
//  ConnectModel.m
//  5.5解析作业
//
//  Created by dllo on 15/5/7.
//  Copyright (c) 2015年 dllo. All rights reserved.
//

#import "ConnectModel.h"
#import <objc/runtime.h>
#import <Foundation/NSObjCRuntime.h>
#import "Reachability.h"
#import "Tools.h"
@implementation ConnectModel
- (void)dealloc
{
    [_requestUrl release];
    [super dealloc];
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        
    }
    return self;
}

#pragma mark -
#pragma 判断是否有网封装
- (BOOL)stringFromStatus:(NetworkStatus)status
{
    BOOL a = YES;
    switch (status) {
        case NotReachable:
            a = NO;
            break;
        case ReachableViaWiFi:
        case ReachableViaWWAN:
            break;
        default:
            a = NO;
            break;
    }
    return a;
}
+ (ConnectModel *)connectWithUrl:(NSString *)url delegate:(id<ConnectModelDelegate>)delegate parmaters:(NSDictionary *)parmaters
{
    Reachability *reach = [Reachability reachabilityForInternetConnection];
    NetworkStatus status = [reach currentReachabilityStatus];
    if (status) {
        ConnectModel *model = [[ConnectModel alloc] init];
        model.delegate = delegate;
        [model startConnection:url parmaters:parmaters];
        return [model autorelease];
    } else {
        NSString *str = [url stringByAppendingString:[parmaters objectForKey:@"cityid"]];
        str = [str stringByAppendingString:[parmaters objectForKey:@"page"]];
        NSData *data = [Tools readWithName:str directory:NSLibraryDirectory];
        [delegate connectFinished:data];
        return nil;
    }
    
}

- (void)startConnection:(NSString *)str parmaters:(NSDictionary *)parmaters
{
    NSString *delegateDescription = [[self.delegate class] description];
    classIsa = (int)objc_getClass([delegateDescription UTF8String]);
    
    // 异步网络连接
    NSString *string = [str stringByAppendingString:[parmaters objectForKey:@"cityid"]];
    self.requestUrl = [string stringByAppendingString:[parmaters objectForKey:@"page"]];
    
    NSString *bodyStr = @"--0xKhTmLbOuNdArY";
    
    bodyStr = [bodyStr stringByAppendingString:@"\r\n"];
    
    bodyStr = [bodyStr stringByAppendingString:@"Content-Disposition: form-data; name=\"cityid\"\r\n\r\n"];
    bodyStr = [bodyStr stringByAppendingString:[parmaters objectForKey:@"cityid"]];
    bodyStr = [bodyStr stringByAppendingString:@"\r\n"];
    bodyStr = [bodyStr stringByAppendingString:@"--0xKhTmLbOuNdArY\r\n"];
    bodyStr = [bodyStr stringByAppendingString:@"Content-Disposition: form-data; name=\"page\"\r\n\r\n"];
    bodyStr = [bodyStr stringByAppendingString:[parmaters objectForKey:@"page"]];
    bodyStr = [bodyStr stringByAppendingString:@"\r\n"];
    bodyStr = [bodyStr stringByAppendingString:@"--0xKhTmLbOuNdArY--"];
    
    
    // NSLog(@"%@", bodyStr);
    
    
    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    
    NSURL *url = [NSURL URLWithString:str];
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    
    [request setHTTPMethod:@"POST"];
    [request setValue:@"multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY" forHTTPHeaderField:@"Content-Type"];
    
    NSData *data = [bodyStr dataUsingEncoding:NSUTF8StringEncoding];
    
    
    
    [request setHTTPBody:data];
    [NSURLConnection connectionWithRequest:request delegate:self];
    
    //    POST http://m.goufang.com/api/loupan/hometuijian HTTP/1.1
    //Host: m.goufang.com
    //    Proxy-Connection: keep-alive
    //    Content-Type: multipart/form-data; charset=utf-8; boundary=0xKhTmLbOuNdArY
    //    Content-Length: 162
    //Connection: keep-alive
    //Cookie: ASP.NET_SessionId=khkjhvak2mobhfi34pgdaqc5
    //    User-Agent: Paros/3.2.13
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    self.receiveData = [NSMutableData data];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [_receiveData appendData:data];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSStringEncoding enc = CFStringConvertEncodingToNSStringEncoding (kCFStringEncodingGB_18030_2000);
    NSString *value = [[NSString alloc] initWithData:_receiveData encoding:enc];
    NSData *data = [value dataUsingEncoding:NSUTF8StringEncoding];
    [self.delegate connectFinished:data];
    [Tools writeWithName:self.requestUrl data:data directory:NSLibraryDirectory];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"error = %@", error);
}



@end
